package com.bitejiuyeke.job_publish.interceptor;

import com.bitejiuyeke.job_publish.config.AppConfig;
import com.bitejiuyeke.job_publish.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 比特就业课
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 预处理(请求的前置处理)回调方法<br/>
     * 返回值: <br/>true 流程继续;<br/>
     *        false流程中断, 不会再调用其他的拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从header中获取token
        String jwtToken = request.getHeader(AppConfig.HEADER_USER_TOKEN);
        log.info("从header中获取token:{}",jwtToken);
        //验证用户token
        Claims claims = JWTUtils.parseJWT(jwtToken);
        if (claims!=null){
            // 获取用户Id和用户名
            Long userId = Long.valueOf((String) claims.get(AppConfig.TOKEN_USER_ID));
            String userName = (String) claims.get(AppConfig.TOKEN_USER_NAME);
            // 把用户ID和用户名设置到request
            request.setAttribute(AppConfig.TOKEN_USER_ID, userId);
            request.setAttribute(AppConfig.TOKEN_USER_NAME, userName);
            log.info("令牌验证通过, 放行");
            return true;
        }
        // 状态码
        response.setStatus(401);
        return false;
    }
}
